package rabbitmq;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import rabbitmq.model.User;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消息生成者
 * Virtual Hosts queue
 * 一个用户可以对应多个Virtual Hosts，一个Virtual Hosts可以创建多个queue，过个Virtual Hosts之间相互独立
 */
public class Producer2 {

	/**
	 * 采用默认exchange方式，默认exchange为direct类型
	 * fanout:广播到同一exchange下所有队列，此事RoutingKey的设置不起作用
	 * direct:发送消息到同一exchange下拥有相同routing_key下的所有队列
	 * @param args
	 * @throws IOException
	 * @throws TimeoutException
	 */
	public static void main(String[] args) throws IOException, TimeoutException {
		Connection connection = null;
		Channel channel = null;
		try {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost("127.0.0.1");
			factory.setPort(5672);
			factory.setUsername("test");
			factory.setPassword("test");
			factory.setVirtualHost("test_vhosts");

			//创建与RabbitMQ服务器的TCP连接
			connection  = factory.newConnection();
			channel = connection.createChannel();

			/**
			 * 声明队列，如果队列已存在，则直接写入,如队列不存在则会创建队列
			 * durable=true 设置队列持久化
			 */
			channel.queueDeclare("Python", true, false, false, null);
			String message ;

			long startTime = System.currentTimeMillis();
			for (int i = 0; i <1000 ; i++) {
				User user = new User();
				user.setId(i+1);
				user.setName("Hubert"+(i+1));
				user.setSex(i+1);
				message = JSON.toJSONString(user);

				/**
				 * 默认exchange，类型为direct,默认routingKey与queue相同；
				 * 因为与默认exchange绑定，所以就算绑定其他类型的exchange，用此默认exchange也可以写入。
				 * 设置BasicProperties props为MessageProperties.PERSISTENT_TEXT_PLAIN将消息持久化，设置为null，则不持久化
				 */
				channel.basicPublish("", "Python", MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());

				System.out.println("Send Message is:'" + message + "'");
			}
			System.out.println(System.currentTimeMillis() - startTime);
		} catch(Exception ex) {
			ex.printStackTrace();
		} finally {
			if(channel != null) {
				channel.close();
			}
			if(connection != null) {
				connection.close();
			}
		}
	}
}
